package top.skihub;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@EnableFeignClients
@SpringBootApplication
@EnableDiscoveryClient  // 添加服务发现注解
public class TliasWebSmartshoppingApplication {
    private static final Logger logger = LoggerFactory.getLogger(TliasWebSmartshoppingApplication.class);

    public static void main(String[] args) {
        // 设置默认配置文件为gateway
        String profile = System.getProperty("spring.profiles.active", "gateway");
        System.setProperty("spring.profiles.active", profile);
        
        SpringApplication app = new SpringApplication(TliasWebSmartshoppingApplication.class);
        ConfigurableApplicationContext context = app.run(args);
        
        String port = context.getEnvironment().getProperty("server.port");
        String serviceName = context.getEnvironment().getProperty("spring.application.name");
        String group = context.getEnvironment().getProperty("spring.cloud.nacos.discovery.group");
        
        logger.info("服务启动成功: {} (Group: {}) on port: {}", serviceName, group, port);
    }

    @RestController
    class EchoController {
        @RequestMapping(value = "/echo/{string}", method = RequestMethod.GET)
        public String echo(@PathVariable String string) {
            return "Hello Nacos Discovery " + string;
        }
    }

    @LoadBalanced
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    @RestController
    public class TestController {
        private final RestTemplate restTemplate;

        @Autowired
        public TestController(RestTemplate restTemplate) {
            this.restTemplate = restTemplate;
        }

        @RequestMapping(value = "/echo/{str}", method = RequestMethod.GET)
        public String echo(@PathVariable String str) {
            return restTemplate.getForObject("http://service-provider/echo/" + str, String.class);
        }
    }
}